package model

// by daoyi
import (
	"errors"
	"simai_oa/tool"
	"time"
)

// Category 商品分类表
type Category struct {
	ID               int32       `gorm:"primarykey;type:int" json:"id" form:"id"`
	Name             string      `gorm:"type:varchar(50);not null;comment:分类名称" json:"name" form:"name"`
	ParentCategoryID int32       `grom:"column:parent_id" json:"parent_id" form:"parent_id"`
	ParentCategory   *Category   `json:"-"`
	SubCategory      []*Category `gorm:"foreignKey:ParentCategoryID;references:ID" json:"sub_category" form:"sub_category"`
	Level            int32       `gorm:"column:level;default:1;not null;type:int;comment:分类的级别" json:"level" form:"level"`
	IsTab            bool        `gorm:"comment:是否显示;default:false" json:"is_tab" form:"is_tab"`
	Sort             int32       `gorm:"comment:分类排序;default:99;not null;type:int" json:"sort" form:"sort"`
	CreatedAt        string      `gorm:"column:create_at" json:"created_at" form:"created_at"`
	UpdatedAt        string      `gorm:"column:update_at" json:"updated_at" form:"updated_at"`
	DeletedAt        time.Time   `json:"deleted_at"`
}

type CategoryInfo struct {
	ID             int32
	Name           string
	ParentCategory int32
	Level          int32
	IsTab          bool
	Sort           int32
}

func AddCategory(req *CategoryInfo) (*CategoryInfo, error) {
	cMap := map[string]interface{}{}
	cMap["name"] = req.Name
	cMap["level"] = req.Level
	cMap["is_tab"] = req.IsTab
	cMap["sort"] = req.Sort
	cMap["create_at"] = tool.GetDate()
	cMap["update_at"] = tool.GetDate()

	// 去查询父类目是否存在
	if req.Level != 1 {
		var categories Category
		if res := tool.Gdb.First(&categories, req.ParentCategory); res.RowsAffected == 0 {
			return nil, errors.New("商品分类不存在")
		}
		cMap["parent_category_id"] = req.ParentCategory
	}

	result := tool.Gdb.Model(&Category{}).Create(&cMap)
	if result.Error != nil {
		return nil, result.Error
	}
	var value int32
	value, ok := cMap["parent_category_id"].(int32)
	if !ok {
		value = 0
	}
	res := &CategoryInfo{
		Name:           cMap["name"].(string),
		ParentCategory: value,
		Level:          cMap["level"].(int32),
		IsTab:          cMap["is_tab"].(bool),
		Sort:           cMap["sort"].(int32),
	}
	return res, nil
}

func UpdateCategory(req *CategoryInfo) (*CategoryInfo, error) {
	cMap := map[string]interface{}{}
	cMap["id"] = req.ID
	cMap["name"] = req.Name
	cMap["level"] = req.Level
	cMap["is_tab"] = req.IsTab
	cMap["sort"] = req.Sort
	cMap["create_at"] = tool.GetDate()
	cMap["update_at"] = tool.GetDate()

	// 去查询父类目是否存在
	if req.Level != 1 {
		var categories Category
		if res := tool.Gdb.First(&categories, req.ParentCategory); res.RowsAffected == 0 {
			return nil, errors.New("商品分类不存在")
		}
		cMap["parent_category_id"] = req.ParentCategory
	}

	result := tool.Gdb.Model(&Category{}).Save(&cMap)
	if result.Error != nil {
		return nil, result.Error
	}
	var value int32
	value, ok := cMap["parent_category_id"].(int32)
	if !ok {
		value = 0
	}
	res := &CategoryInfo{
		ID:             cMap["id"].(int32),
		Name:           cMap["name"].(string),
		ParentCategory: value,
		Level:          cMap["level"].(int32),
		IsTab:          cMap["is_tab"].(bool),
		Sort:           cMap["sort"].(int32),
	}
	return res, nil
}

// 删除角色及关联数据
func (Category) Delete(roleids []uint64) error {
	tx := tool.Gdb.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		tx.Rollback()
		return err
	}
	if err := tx.Where("id in (?)", roleids).Delete(&Category{}).Error; err != nil {
		tx.Rollback()
		return err
	}
	//删除关联表中数据
	//if err := tx.Where("role_id in (?)", roleids).Delete(&RoleMenu{}).Error; err != nil {
	//	tx.Rollback()
	//	return err
	//}
	return tx.Commit().Error
}
